package com.bestdata.TD440.emNewModel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author liuao
 * @version 1.0.0
 * @projectName guns-vip
 * @title: NewMessageSend
 * @description: 新版本报文发送服务
 * @date 2020/3/219:17
 */
@Configuration
public class NewMessageSend {

    //转发是否启用
    private static boolean transmissionInuse;

    //转发类型
    private static String transmissionType;

    //转发地址
    private static String transmissionIp;

    //转发端口
    private static Integer transmissionPort;

    private static NewMessageSend messageSend = new NewMessageSend();

    private Logger logger = LoggerFactory.getLogger(NewMessageSend.class);


    public static void newMessageSendCore(String message){
        if(transmissionInuse && transmissionType.equalsIgnoreCase("UDP")){
            messageSend.messageTransmission(message,transmissionIp,transmissionPort);
        }
    }

    private void messageTransmission(String message, String transIp, Integer transPort) {
        DatagramSocket datagramSocket=null;
        try {
            //实例化套接字，并指定发送端口
            datagramSocket=new DatagramSocket();
            //指定数据目的地的地址，以及目标端口
            InetAddress destination=InetAddress.getByName(transIp);
            DatagramPacket datagramPacket=
                    new DatagramPacket(message.getBytes(), message.getBytes().length,destination,transPort);
            //发送数据
            datagramSocket.send(datagramPacket);
            logger.info("udpdatasend"+"addr->"+transIp+":"+transPort+"、message->"+message);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            datagramSocket.close();
        }
    }

    @Value("${transmission.inuse}")
    public void setTransmissionInuse(boolean transmissionInuse) {
        NewMessageSend.transmissionInuse=transmissionInuse;
    }

    @Value("${transmission.type}")
    public void setTransmissionType(String transmissionType) {
        NewMessageSend.transmissionType=transmissionType;
    }

    @Value("${transmission.ip}")
    public void setTransmissionIp(String transmissionIp) {
        NewMessageSend.transmissionIp=transmissionIp;
    }

    @Value("${transmission.port}")
    public void setTransmissionPort(Integer transmissionPort) {
        NewMessageSend.transmissionPort=transmissionPort;
    }
}
